/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.upload.server;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class UploadedFileManager implements HttpSessionBindingListener {

    protected Map<String, UploadedFile> files = new HashMap<String, UploadedFile>();

    public void put(UploadedFile file) {
        synchronized (this) {
            files.put(file.getId(), file);
        }
    }

    public FileHolder get(String id) {
        synchronized (this) {
            return files.get(id);
        }
    }

    public FileHolder remove(String id) {
        synchronized (this) {
            return files.remove(id);
        }
    }

    public void clear() {
        UploadedFile[] ar;
        synchronized (this) {
            ar = files.values().toArray(new UploadedFile[files.size()]);
            files = new HashMap<String, UploadedFile>();
        }
        for (UploadedFile uf : ar) {
            uf.delete();
        }
    }

    @Override
    public void valueBound(HttpSessionBindingEvent arg0) {
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent arg0) {
        clear();
    }
}
